<template>
  <div class="upload-container" @dragover.prevent="onDragOver" @dragleave.prevent="onDragLeave" @drop.prevent="onDrop"
    :class="{ 'drag-over': isDragOver }">
    <div class="upload-area">
      <p>拖拽文件到这里或</p>
      <input type="file" ref="fileInput" @change="onFileChange" accept="image/*,video/*" multiple
        style="display: none" />
      <button @click="triggerFileInput">选择文件</button>
      <p class="hint">支持格式：JPEG, PNG, GIF, MP4, AVI</p>
    </div>

    <!-- 文件列表 -->
    <div v-if="files.length > 0" class="file-list">
      <div v-for="(file, index) in files" :key="index" class="file-item">
        <!-- 图片预览 -->
        <img v-if="file.type && file.type.startsWith('image/')" :src="file.previewUrl" alt="图片预览" class="preview" />

        <!-- 视频预览 -->
        <video v-else-if="file.type && file.type.startsWith('video/')" :src="file.previewUrl" controls
          class="preview"></video>

        <!-- 未知类型文件 -->
        <div v-else class="unknown-file">
          <p>不支持预览</p>
        </div>

        <div class="file-info">
          <p>{{ file.name }}</p>
          <p>{{ formatFileSize(file.size) }}</p>
          <button @click="removeFile(index)" class="cancel">移除</button>
        </div>
      </div>
    </div>

    <!-- 上传按钮 -->
    <div v-if="files.length > 0" class="upload-actions">
      <button @click="uploadFiles">上传所有文件</button>
      <button @click="clearFiles" class="cancel">清空列表</button>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';

const files = ref([]);
const isDragOver = ref(false);
const fileInput = ref(null);

// 格式化文件大小
const formatFileSize = (size) => {
  if (size > 1024 * 1024) {
    return `${(size / 1024 / 1024).toFixed(1)} MB`;
  } else if (size > 1024) {
    return `${(size / 1024).toFixed(1)} KB`;
  } else {
    return `${size} B`;
  }
};

// 验证文件类型
const validateFileType = (file) => {
  return file.type && (file.type.startsWith('image/') || file.type.startsWith('video/'));
};

// 拖拽事件
const onDragOver = () => {
  isDragOver.value = true;
};

const onDragLeave = () => {
  isDragOver.value = false;
};

const onDrop = (event) => {
  isDragOver.value = false;
  const droppedFiles = event.dataTransfer.files;
  if (droppedFiles.length > 0) {
    handleFiles(droppedFiles);
  }
};

// 文件选择事件
const onFileChange = (event) => {
  const selectedFiles = event.target.files;
  if (selectedFiles.length > 0) {
    handleFiles(selectedFiles);
  }
};

// 处理文件
const handleFiles = (fileList) => {
  for (const file of fileList) {
    if (!validateFileType(file)) {
      alert('请选择图片或视频文件（支持格式：JPEG/PNG/GIF/MP4/AVI）');
      continue;
    }

    const fileWithPreview = {
      ...file,
      previewUrl: URL.createObjectURL(file),
    };
    files.value.push(fileWithPreview);
  }
};

// 触发文件选择
const triggerFileInput = () => {
  fileInput.value.click();
};

// 移除单个文件
const removeFile = (index) => {
  URL.revokeObjectURL(files.value[index].previewUrl);
  files.value.splice(index, 1);
};

// 清空文件列表
const clearFiles = () => {
  files.value.forEach((file) => URL.revokeObjectURL(file.previewUrl));
  files.value = [];
};

// 上传文件
const uploadFiles = async () => {
  if (files.value.length === 0) return;

  const formData = new FormData();
  files.value.forEach((file) => {
    formData.append('files', file);
  });

  try {
    // 示例上传请求
    // await axios.post('/api/upload', formData)
    alert('文件上传成功！');
    clearFiles();
  } catch (error) {
    alert('上传失败，请重试');
  }
};
</script>

<style lang="scss" scoped>
.upload-container {
  width: 100%;
  max-width: 600px;
  min-height: 300px;
  border: 2px dashed #ccc;
  border-radius: 12px;
  padding: 20px;
  box-sizing: border-box;
  transition: all 0.3s ease;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin: 0 auto;

  &.drag-over {
    border-color: #409eff;
    background-color: rgba(64, 158, 255, 0.05);
  }

  .upload-area {
    text-align: center;
    padding: 20px;

    p {
      margin: 10px 0;
      color: #666;

      &.hint {
        font-size: 12px;
        color: #999;
      }
    }

    button {
      padding: 10px 24px;
      background-color: #409eff;
      color: white;
      border: none;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background-color: #79bbff;
      }
    }
  }

  .file-list {
    width: 100%;
    margin-top: 20px;

    .file-item {
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      padding: 10px;
      border: 1px solid #eee;
      border-radius: 8px;

      .preview {
        width: 60px;
        height: 60px;
        object-fit: cover;
        border-radius: 6px;
        margin-right: 10px;
      }

      .unknown-file {
        width: 60px;
        height: 60px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: #f0f0f0;
        border-radius: 6px;
        margin-right: 10px;

        p {
          font-size: 12px;
          color: #999;
        }
      }

      .file-info {
        flex: 1;

        p {
          margin: 2px 0;
          font-size: 14px;
          color: #333;
        }

        button {
          padding: 4px 10px;
          background-color: #f56c6c;
          color: white;
          border: none;
          border-radius: 4px;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            background-color: #f78989;
          }
        }
      }
    }
  }

  .upload-actions {
    margin-top: 20px;

    button {
      padding: 10px 24px;
      background-color: #409eff;
      color: white;
      border: none;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s;
      margin: 0 8px;

      &.cancel {
        background-color: #f56c6c;

        &:hover {
          background-color: #f78989;
        }
      }

      &:hover {
        background-color: #79bbff;
      }
    }
  }
}

/* 手机端适配 */
@media (max-width: 600px) {
  .upload-container {
    padding: 10px;

    .upload-area {
      padding: 10px;

      button {
        padding: 8px 16px;
      }
    }

    .file-list .file-item {
      flex-direction: column;
      align-items: flex-start;

      .preview,
      .unknown-file {
        width: 100%;
        height: auto;
        margin-bottom: 10px;
      }

      .file-info {
        width: 100%;
      }
    }

    .upload-actions {
      display: flex;
      flex-direction: column;
      gap: 10px;

      button {
        width: 100%;
        margin: 0;
      }
    }
  }
}
</style>